//
// Created by Administrator on 2020/10/27.
//

#include "l1IntfDl.h"
#include "../l1ApiAdpt/l1ApiAdpt.h"

void RAN_L2_L1I_DL_PotRanProcess()
{
    uint32_t size;
    S_RanCommMsgHdr *pCommMsgHdr;

    while (1)
    {
        pCommMsgHdr = VarRB_ReadRequest(gpRanL2Context->pL3iL1iMsgQue, &size);
        IF_BREAK(==, NULL, pCommMsgHdr, NO_LOG_MESSAGE);

        switch (pCommMsgHdr->type)
        {
        case RAN_L1_API_MSG_PARAMS_REQ:
            CSP_LOG_INF(RAN_MD_L2_L1I, "RAN_L2_L1I_DL_PotRanProcess() recv RAN_L1_API_MSG_PARAMS_REQ\n");
            gpRanL1ApiAdpt->ParamsReq(pCommMsgHdr);
            break;
        case RAN_L1_API_MSG_CONFIG_REQ:
            CSP_LOG_INF(RAN_MD_L2_L1I, "RAN_L2_L1I_DL_PotRanProcess() recv RAN_L1_API_MSG_CONFIG_REQ\n");
            gpRanL1ApiAdpt->ConfigReq(pCommMsgHdr);
            break;
        case RAN_L1_API_MSG_START_REQ:
            CSP_LOG_INF(RAN_MD_L2_L1I, "RAN_L2_L1I_DL_PotRanProcess() recv RAN_L1_API_MSG_START_REQ\n");
            gpRanL1ApiAdpt->StartReq(pCommMsgHdr);
            break;
        default:
            CSP_LOG_WRN(RAN_MD_L2_L1I, "RAN_L2_L1I_DL_PotRanProcess() recv unsupport msg[%#x]\n", pCommMsgHdr->type);
            break;
        }
        VarRB_ReadConsume(gpRanL2Context->pL3iL1iMsgQue, pCommMsgHdr);
    }
}

void RAN_L2_L1I_DL_TtiProcess(int32_t event, int fd, void *data)
{
    int32_t rc;

    S_OsSelectInd indMsg;
    rc = OS_SelectRecvByFd(fd, &indMsg);
    IF_RETURN(!=, O5G_RC_OK, rc, NO_RETURN_VALUE, "RAN_L2_L1I_DL_TtiProcess() OS_SelectRecv() error!\n");

    switch (indMsg.ind)
    {
    case RAN_L2_INTRA_IND_MSG_TTI_IND:
//        CSP_LOG_INF(RAN_MD_L2_L1I, "RAN_L2_L1I_DL_TtiProcess() recv RAN_L2_INTRA_IND_MSG_TTI_IND. data[%lu]\n", indMsg.data);
        gpRanL1ApiAdpt->TtiProc((S_RanL2CellInst *)indMsg.data, indMsg.sn);
        break;
    default:
        break;
    }
    RAN_L2_L1I_DL_PotRanProcess();
}

void RAN_L2_L1I_DL_PtoProcess()
{
    RAN_L2_L1I_DL_PotRanProcess();
}

void *RAN_L2_L1I_DL_Task(void* arg)
{
    int fd;
    int32_t rc;

    fd = gpRanL2L1IntfContext->dlSelector.recvFd;
    POLLER_Add(gpRanL2L1IntfContext->dlPoller, fd, RAN_L2_L1I_DL_TtiProcess, NULL, NULL, NULL);

    while (1)
    {
        rc = POLLER_Poll(gpRanL2L1IntfContext->dlPoller, 10);
        if (0 == rc)
        {
            /*
             * POLL TIME OUT处理，是为了在L1 START前处理能够处理L3等消息。
             * L1 START后就会有TTI消息上来，就不会超时进入此分支。
             */
            RAN_L2_L1I_DL_PtoProcess();
        }
        pthread_testcancel();
    }
    return NULL;
}
